<template>
  <div class="app-container">
    <div class="back-item">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
        <el-form-item label="商品品类" prop="firstCategoryId" >
          <el-cascader
            v-model="categoryIds.queryIds"
            :options="categoryTree"
            :props="{label:'categoryName',value:'categoryId'}"
            @change="handleQuerySort"
            placeholder="请选择品类信息"
            filterable
            :clearable="true"
          />
        </el-form-item>
        <el-form-item label="规格名" prop="standardName" >
          <el-input
              v-model="queryParams.standardName"
              placeholder="请输入规格名"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button type="warning" icon="Refresh" size="mini" @click="resetQuery">重置</el-button>
          <el-button size="mini" @click="changSearch">{{showSearch?"常用条件":"所有条件"}}</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="back-item">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
              type="primary"
              plain
              icon="Plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['mall:standard:add']"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              type="success"
              plain
              icon="Edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['mall:standard:edit']"
          >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              type="danger"
              plain
              icon="Delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['mall:standard:remove']"
          >删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              type="warning"
              plain
              icon="Download"
              size="mini"
              :loading="exportLoading"
              @click="handleExport"
              v-hasPermi="['mall:standard:export']"
          >导出
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="standardList"
          @selection-change="handleSelectionChange"
          @row-dblclick="handleDetails"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="序号" align="center" prop="standardId" v-if="columns[0].visible">
          <template #default="scope">
            {{scope.$index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize}}
          </template>
        </el-table-column>
        <el-table-column label="商品品类" align="center" prop="firstCategoryId" v-if="columns[1].visible">
          <template #default="scope">
            {{`${categoryNames[scope.row.firstCategoryId]}/${categoryNames[scope.row.secondCategoryId]}/${categoryNames[scope.row.thirdCategoryId]}`}}
          </template>
        </el-table-column>
        <el-table-column label="规格名" align="center" prop="standardName" v-if="columns[2].visible"/>
        <el-table-column label="规格值" align="center" prop="standardArr" v-if="columns[3].visible"/>
        <el-table-column label="操作" align="center" width="200" fixed="right" class-name="small-padding fixed-width"
            v-if="columns[4].visible"
        >
          <template #default="scope">
            <el-button
                size="mini"
                type="text"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['mall:standard:edit']"
            >修改
            </el-button>
            <el-button
                size="mini"
                type="text"
                icon="Document"
                @click="handleDetails(scope.row)"
                v-hasPermi="['mall:standard:query']"
            >详情
            </el-button>
            <el-button
                size="mini"
                type="text"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['mall:standard:remove']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
      />
      <div class="line-magin"></div>
    </div>
    <!-- 添加或修改预设规格对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="standardForm" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品品类" prop="firstCategoryId">
          <el-cascader
            v-model="categoryIds.formIds"
            :options="categoryTree"
            :props="{label:'categoryName',value:'categoryId'}"
            @change="handleFormSort"
            placeholder="请选择品类信息"
            filterable
          />
        </el-form-item>
        <el-form-item label="规格名" prop="standardName">
          <el-input v-model="form.standardName" placeholder="请输入规格名"/>
        </el-form-item>
        <el-form-item label="规格值" prop="standard">
          <el-row :gutter="20" v-for="(item,index) in form.standardValue" :key="index">
            <el-col :span="17">
              <el-input v-model="item.value" placeholder="请输入内容"/>
            </el-col>

            <el-col :span="7" >
              <el-button
                size="mini" type="text"
                icon="Edit" @click="addStandardValue(index)"
              >新增
              </el-button>
              <el-button v-if="index!=0"
                size="mini" type="text" icon="Delete"
                style="color: red" @click="delStandardValue(index)"
              >删除
              </el-button>
            </el-col>

          </el-row>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 预设规格详情对话框 -->
    <el-dialog class="detail-form" :title="title" v-model="open2" width="700px" append-to-body>
      <el-form ref="standardDetail" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="一级品类" prop="firstCategoryId">
        {{ form.firstCategoryId }}
      </el-form-item>
      <el-form-item label="二级品类" prop="secondCategoryId">
        {{ form.secondCategoryId }}
      </el-form-item>
      <el-form-item label="三级品类" prop="thirdCategoryId">
        {{ form.thirdCategoryId }}
      </el-form-item>
      <el-form-item label="规格名" prop="standardName">
        {{ form.standardName }}
      </el-form-item>
      <el-form-item label="规格值" prop="standard">
        {{ form.standardArr }}
      </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Standard">
  import { listStandard, getStandard, delStandard, addStandard, updateStandard } from "@/api/mall/standard";
  import { treeListCategory, listCategory } from "@/api/mall/category";
  const { proxy } = getCurrentInstance();

  // 遮罩层
  const loading = ref(true);
  // 导出遮罩层
  const exportLoading = ref(false);
  // 选中数组
  const ids = ref([]);
  // 非单个禁用
  const single = ref(true);
  // 非多个禁用
  const multiple = ref(true);
  // 切换搜索条件
  const showSearch = ref(false);
  // 总条数
  const total = ref(0);
  // 预设规格表格数据
  const standardList = ref([]);
  //商品品类树
  const categoryTree = ref([]);
  const categoryNames = ref({});
  // 弹出层标题
  const title = ref("");
  // 弹出层
  const open = ref(false);
  const open2 = ref(false);
  const data = reactive({
    // 列信息
    columns: [
      {key: 0, label: `序号`, visible: true},
      {key: 1, label: `商品品类`, visible: true},
      {key: 2, label: `规格名`, visible: true},
      {key: 3, label: `规格值`, visible: true},
      {key: 4, label: `操作`, visible: true},
    ],
    // 表单参数
    form:{},
    // 查询参数
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      firstCategoryId: null,
      secondCategoryId: null,
      thirdCategoryId: null,
      standardName: null,
      standard: null,
    },
    rules: {
    },
    categoryIds: {
      queryIds: [],
      formIds: [],
    }
  });
  const { columns, queryParams, form, rules, categoryIds } = toRefs(data);

  /** 查询预设规格列表 */
  function getList() {
    loading.value = true;
    listStandard(queryParams.value).then(response => {
      standardList.value = response.rows;
      total.value = response.total;
      loading.value = false;
      for (let item of standardList.value){
        let standardArr = [];
        let standardValue = [];
        if (item.standard){
          standardValue = JSON.parse(item.standard);
        }else {
          standardValue = [{value:""}]
        }
        for (let item2 of standardValue){
          standardArr.push(item2.value)
        }
        item.standardArr = standardArr.toString()
      }
    });

  }
  //获取树形品类列表
  function getCategoryTree(){
    treeListCategory().then(response => {
      categoryTree.value = response.data
      setCategoryNames(categoryTree.value)
    })
  }
  //设置品类名map
  function setCategoryNames(categoryTree) {
    for (let item of categoryTree){
      categoryNames.value[item.categoryId] = item.categoryName
      if (item.children && item.children.length){
        setCategoryNames(item.children)
      }
    }
  }
  /** 品类选择-query */
  function handleQuerySort(values){
    if (values&&values.length == 3){
      queryParams.value.firstCategoryId = values[0];
      queryParams.value.secondCategoryId = values[1];
      queryParams.value.thirdCategoryId = values[2];
    }else {
      if(values){
        categoryIds.value.queryIds = [];
        proxy.$modal.msgWarning("请选择完整品类!")
      }
      queryParams.value.firstCategoryId = null;
      queryParams.value.secondCategoryId = null;
      queryParams.value.thirdCategoryId = null;

    }

  }
  /** 品类选择-form */
  function handleFormSort(values){
    if (values&&values.length == 3){
      form.value.firstCategoryId = values[0];
      form.value.secondCategoryId = values[1];
      form.value.thirdCategoryId = values[2];
    }else {
      if(values){
        categoryIds.value.formIds = [];
        proxy.$modal.msgWarning("请选择完整品类!")
      }
      form.value.firstCategoryId = null;
      form.value.secondCategoryId = null;
      form.value.thirdCategoryId = null;
    }
  }
  /** 取消按钮 */
  function cancel() {
    open.value = false;
    open2.value = false;
    reset();
  }
  /** 表单重置 */
  function reset() {
    form.value = {
      standardId: null,
      firstCategoryId: null,
      secondCategoryId: null,
      thirdCategoryId: null,
      standardName: null,
      standard: null,
      standardValue: [{value:null}],
      createTime: null,
      createBy: null,
      updateTime: null,
    };
    proxy.resetForm("userForm");
    categoryIds.value.formIds = [];
  }
  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef");
    queryParams.value.firstCategoryId = null;
    queryParams.value.secondCategoryId = null;
    queryParams.value.thirdCategoryId = null;
    handleQuery();
  }
  /** 切换按钮操作 */
  function changSearch() {
    showSearch.value = !showSearch.value;
  }
  /** 多选框选中数据 */
  function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.standardId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }
  /** 新增按钮操作 */
  function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加预设规格";
  }
  /** 修改按钮操作 */
  function handleUpdate(row) {
    reset();
    const standardId = row.standardId || ids.value

    getStandard(standardId).then(response => {
      form.value = response.data;
      categoryIds.value.formIds = [ form.value.firstCategoryId, form.value.secondCategoryId, form.value.thirdCategoryId ]
      if (form.value.standard){
        form.value.standardValue = JSON.parse(form.value.standard);
      }else {
        form.value.standardValue = [{value:""}]
      }
      open.value = true;
      title.value = "修改预设规格";
    });
  }
  /** 详情按钮操作 */
  function handleDetails(row) {
    reset();
    const standardId = row.standardId || ids.value
    getStandard(standardId).then(response => {
      form.value = response.data;
      let standardArr = []
      if (form.value.standard){
        form.value.standardValue = JSON.parse(form.value.standard);
      }else {
        form.value.standardValue = [{value:""}]
      }
      for (let item of form.value.standardValue){
        standardArr.push(item.value)
      }
      form.value.standardArr = standardArr.toString();
      open2.value = true;
      title.value = "修改预设规格";
    });
  }
  /** 提交按钮操作 */
  function submitForm() {
    form.value.standard = JSON.stringify(form.value.standardValue)
    proxy.$refs["standardForm"].validate(valid => {
      if (valid) {
        if (form.value.standardId) {
          updateStandard(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        } else {
          addStandard(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        }
      }
    })
  }
  /** 删除按钮操作 */
  function handleDelete(row) {
    const standardIds = row.standardId || ids.value;
    proxy.$modal.confirm('是否确认删除预设规格编号为\"' + standardIds + '\"的数据项?').then(() => {

      return delStandard(standardIds);
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});
  }
  /** 导出按钮操作 */
  function handleExport() {
    exportLoading.value = true;
    proxy.download("system/post/export", {
      ...queryParams.value
    }, `预设规格表_${new Date().getTime()}.xlsx`).then(response => {
      exportLoading.value = false;
    }).catch(error => {
      exportLoading.value = false;
    });
  }

  /** 新增规格值 */
  function addStandardValue(index) {
    let standardValue = {value: ""};
    form.value.standardValue.splice(index+1,0,standardValue);
  }

  /** 删除规格值 */
  function delStandardValue(standardValue,index){
    console.log(standardValue);
    form.value.standardValue.splice(index,1);

  }

  getCategoryTree();
  getList();
</script>
<style>
  .el-row {
    margin-bottom: 10px;
  }
</style>
